package factorytest.iflytek.com.einkiflytekfactorytest.factorytestui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import factorytest.iflytek.com.einkiflytekfactorytest.R;
import factorytest.iflytek.com.einkiflytekfactorytest.common.PermissionManager;
import factorytest.iflytek.com.einkiflytekfactorytest.config.EinkProperty;
import factorytest.iflytek.com.einkiflytekfactorytest.device.DeviceAttr;
import factorytest.iflytek.com.einkiflytekfactorytest.iflytekWakeup.HtfyunWakeupEngine;
import factorytest.iflytek.com.einkiflytekfactorytest.iflytekWakeup.HtfyunWakeuperListener;

/**
 * Created by sst on 2018/7/10.
 */

public class FactoryThirdActivity_bk extends FactoryBaseActivity {


    private Button btnPower;
    private Button btnHome;
    private Button btnHall;
    private Button btnBack;

    private final int FLAG_KEY_POWER = 0x01;
    private final int FLAG_KEY_HOME = 0x02;
    private final int FLAG_KEY_HALL = 0x04;
    private final int FLAG_KEY_BACK = 0x08;

    private int flagKeyTest = FLAG_KEY_POWER | FLAG_KEY_HOME | FLAG_KEY_HALL | FLAG_KEY_BACK;

    ////////////////////////////////////////////////
    private static final int WAKE_UP_TIME_SECOND = 40;
    private static final int SUCCESS_WAKEUP_COUNT = 3;

    private View layoutWakeup;
    private TextView txtStatus;
    private TextView txtCount;
    private TextView txtTips;
    private TextView txtCountDown;

    private HtfyunWakeupEngine wakeupEngine;

    private int wakeupCount = 0;
    private boolean canWakeup = false;
    private int wakeupCountDown = WAKE_UP_TIME_SECOND;


    private static final int MSG_WAKEUP_START = 100;
    private static final int DELAY_WAKEUP_START = 100;
    private static final int MSG_WAKEUP_COUNT_DOWN = 1000;
    private static final int PERIOD_WAKEUP_COUNT_DOWN = 1000;


    @Override
    int getLayoutId() {
        return R.layout.activity_factory_third;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {

        btnPower = (Button) findViewById(R.id.btnPower);
        btnHome = (Button) findViewById(R.id.btnHome);
        btnHall = (Button) findViewById(R.id.btnHall);
        btnBack = (Button) findViewById(R.id.btnBack);

        txtStatus = (TextView) findViewById(R.id.txtStatus);
        txtCount = (TextView) findViewById(R.id.txtCount);
        txtTips = (TextView) findViewById(R.id.txtTips);
        txtCountDown = (TextView) findViewById(R.id.txtCountDown);

        DeviceAttr deviceAttr = DeviceAttr.getRunningDeviceAttr();
        if (!deviceAttr.hasHomeKey()) {
            btnHome.setVisibility(View.GONE);
            flagKeyTest &= ~FLAG_KEY_HOME;
        }

        if (!deviceAttr.hasBackKey()) {
            btnBack.setVisibility(View.GONE);
            flagKeyTest &= ~FLAG_KEY_BACK;
        }

        if (!deviceAttr.hasHallKey()) {
            btnHall.setVisibility(View.GONE);
            flagKeyTest &= ~FLAG_KEY_HALL;
        }


        txtTips.setText(getString(R.string.test_wakeup_tips, WAKE_UP_TIME_SECOND));
        txtCount.setText(getString(R.string.wakeup_success_count, wakeupCount, (SUCCESS_WAKEUP_COUNT - wakeupCount)));
        txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.wakeup_status_start_recognition)));


        layoutWakeup = findViewById(R.id.layoutWakeup);
        layoutWakeup.setVisibility(View.INVISIBLE);
        initPermission();
    }


    @Override
    protected void onResume() {
        super.onResume();
        EinkProperty.setEinkFactoryTestEnabled(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EinkProperty.setEinkFactoryTestEnabled(false);
        stopWakeupTest();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_HOME) {

            btnHome.setSelected(true);

            return true;

        } else if (keyCode == KeyEvent.KEYCODE_BACK) {

            btnBack.setSelected(true);

            return true;

        } else if (keyCode == KeyEvent.KEYCODE_POWER) {

            btnPower.setSelected(true);
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_SLEEP) {

            btnHall.setSelected(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        boolean ret = true;

        if (keyCode == KeyEvent.KEYCODE_HOME) {

            btnHome.setSelected(false);
            btnHome.setText(getNewTextForBtn(btnHome, getResources().getString(R.string.test_ok)));

            flagKeyTest &= ~FLAG_KEY_HOME;


        } else if (keyCode == KeyEvent.KEYCODE_BACK) {

            btnBack.setSelected(false);
            btnBack.setText(getNewTextForBtn(btnBack, getResources().getString(R.string.test_ok)));

            flagKeyTest &= ~FLAG_KEY_BACK;

        } else if (keyCode == KeyEvent.KEYCODE_POWER) {

            btnPower.setSelected(false);
            btnPower.setText(getNewTextForBtn(btnPower, getResources().getString(R.string.test_ok)));

            flagKeyTest &= ~FLAG_KEY_POWER;

        } else if (keyCode == KeyEvent.KEYCODE_SLEEP) {

            btnHall.setSelected(false);
            btnHall.setText(getNewTextForBtn(btnHall, getResources().getString(R.string.test_ok)));

            flagKeyTest &= ~FLAG_KEY_HALL;

//        } else if (keyCode == KeyEvent.KEYCODE_WAKEUP) {
//
//            btnHall.setSelected(false);
//            btnHall.setText(getNewTextForBtn(btnHall, getResources().getString(R.string.test_ok)));
//
//            flagKeyTest &= ~FLAG_KEY_HALL;
//
//            ret = true;
        } else {

            ret = false;
        }

        if (ret && flagKeyTest == 0) {
            startWakeupTest();
        }

        return ret || super.onKeyUp(keyCode, event);
    }

    private String getNewTextForBtn(Button btn, String test_status) {
        String text = btn.getText().toString();
        String arrow = getResources().getString(R.string.arrow);
        String[] rmStatus = text.split(arrow);
        if (rmStatus.length > 1) {
            text = rmStatus[0];
        }
        return (text + arrow + test_status);
    }


    /////////////////////////////////////////////////////////////

    private void startWakeupTest() {
        if (layoutWakeup.getVisibility() == View.VISIBLE) {
            //已经开始唤醒测试了.
            return;
        }
        layoutWakeup.setVisibility(View.VISIBLE);
        startRecognition();
        updateCountdown();
    }

    private void stopWakeupTest() {
        layoutWakeup.setVisibility(View.INVISIBLE);
        stopRecognition();
        getHandler().removeMessages(MSG_WAKEUP_COUNT_DOWN);
    }


    @Override
    void onHandleMessage(Handler handler, Message msg) {

        switch (msg.what) {
            case MSG_WAKEUP_COUNT_DOWN:
                updateCountdown();
                break;
            case MSG_WAKEUP_START:
                if (isRecordGotPermission()) {
                    initIflytekVoiceRecognition();
                } else {
                    initPermission();
                    handler.sendMessageDelayed(msg, DELAY_WAKEUP_START);
                }
                break;
        }
    }



    private boolean isRecordGotPermission() {

        return (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        );

    }

    private void initPermission() {

        if (isRecordGotPermission()) {
            return;
        }

        //同时申请多个权限
        PermissionManager.getInstance(getApplicationContext()).execute(this,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE

        );


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void startRecognition() {
        if(!getHandler().hasMessages(MSG_WAKEUP_START)){
            getHandler().sendEmptyMessageDelayed(MSG_WAKEUP_START, DELAY_WAKEUP_START);
        }
    }

    private void stopRecognition() {
        if(getHandler().hasMessages(MSG_WAKEUP_START)){
            getHandler().removeMessages(MSG_WAKEUP_START);
        }
        destroyIflytekVoiceRecognition();

    }

    private void initIflytekVoiceRecognition() {

        destroyIflytekVoiceRecognition();

        wakeupEngine = new HtfyunWakeupEngine(mContext);
        wakeupEngine.setHtfyunWakeuperListener(new WakeupListener());
        wakeupEngine.start();

        canWakeup = true;

        txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.wakeup_status_doing)));
    }

    private void destroyIflytekVoiceRecognition() {

        if (wakeupEngine != null) {
            wakeupEngine.stop();
            wakeupEngine.destroy();
            wakeupEngine = null;
        }
    }

    private void handleRecognition() {

        wakeupCount++;

        txtCount.setText(getString(R.string.wakeup_success_count, wakeupCount, (SUCCESS_WAKEUP_COUNT - wakeupCount)));

        if (wakeupCount >= SUCCESS_WAKEUP_COUNT) {
            canWakeup = false;
            txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.test_result_pass)));

            finishWithOK();

        } else if (!canWakeup) {

            txtStatus.setText(getString(R.string.wakeup_test_status, getString(R.string.test_result_fail)));
        }
    }

    private void updateCountdown() {

        if (wakeupCountDown <= 0) {
            finishWithFail();
        }

        wakeupCountDown--;
        txtCountDown.setText(getString(R.string.wakeup_test_countdown, wakeupCountDown));

        getHandler().sendEmptyMessageDelayed(MSG_WAKEUP_COUNT_DOWN, PERIOD_WAKEUP_COUNT_DOWN);
    }


    private class WakeupListener implements HtfyunWakeuperListener {
        @Override
        public void onWakeUp(String json) {

            if (!canWakeup) {
                return;
            }
            handleRecognition();
        }

        @Override
        public void onError(String error) {
            Toast.makeText(mContext, error, Toast.LENGTH_LONG).show();
        }
    }
}
